package com.app.util.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


public class RequestUtil {
	
	
	/**
	 * 获取IP地址
	 * @return
	 */
	public static String getIp(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		 String ip = request.getHeader("x-forwarded-for");  
	        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
	            ip = request.getHeader("Proxy-Client-IP");  
	        }  
	        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
	            ip = request.getHeader("WL-Proxy-Client-IP");  
	        }  
	        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
	            ip = request.getRemoteAddr();  
	        }  
	        return ip; 
	}
	
	/**
	 * 以map形式返回http请求参数�?
	 * @param request
	 * @return
	 */
	public static Map<String,String> getRequestMap(HttpServletRequest request){
		Map<String,String> prop = new HashMap<String,String>();
		Map<String,String[]> map = request.getParameterMap();
		for(Map.Entry<String,String[]> entry: map.entrySet()){
			String temp[] = entry.getValue();
			String value = "";
			if(temp!=null && temp.length>0){
				if(temp.length==1){
					value = temp[0];
				}else{
					for(int i=0;i<temp.length;i++){
						if(temp[i].equals("")){
							continue;
						}
						value += temp[i]+",";
					}
					if(!value.equals("")){
						value = value.substring(0,value.length()-1);
					}
				}
			}else{
				value = "";
			}
			prop.put(entry.getKey(), value);
		}
		return prop;
	}

	
	/**
	 * 判断是否是ajax请求
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");  
		
        if("XMLHttpRequest".equalsIgnoreCase(header)){  
            return true;  
        }  
        return false;  
	}
}